package com.chat.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chat.admin.domain.DTO.ADD.AddAuthorityDTO;
import com.chat.admin.domain.DTO.AuthorityDTO;
import com.chat.admin.domain.DTO.EDIT.EditAuthorityDTO;
import com.chat.admin.domain.VO.AuthorityVO;
import com.chat.admin.mapper.AuthorityMapper;
import com.chat.admin.service.IAuthorityService;
import com.chat.common.entity.Admin;
import com.chat.common.entity.Authority;
import com.chat.common.entity.Role;
import com.chat.common.form.ListForm;
import com.chat.common.vo.R;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author weikjie
 * @since 2024-04-14
 */
@Service
public class AuthorityServiceImpl extends ServiceImpl<AuthorityMapper, Authority> implements IAuthorityService {

    @Override
    public R<ListForm<AuthorityVO>> getAuthorityList(AuthorityDTO authorityDTO) {
        QueryWrapper<Authority> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(authorityDTO.getName())){
            queryWrapper.eq("name",authorityDTO.getName());
        }
        if(StringUtils.isNotBlank(authorityDTO.getDescription())){
            queryWrapper.like("description",authorityDTO.getDescription());
        }
        //状态查询
        if(authorityDTO.getState()!=null){
            queryWrapper.eq("state", authorityDTO.getState());
        }
        Page<Authority> authorityPage = new Page<>(authorityDTO.getPage(), authorityDTO.getSize());
        IPage<Authority> authorityIPage = page(authorityPage, queryWrapper);
        List<Authority> AuthorityList = authorityIPage.getRecords();
        List<AuthorityVO> AuthorityVOList = new ArrayList<>();
        for(Authority authority : AuthorityList){
            AuthorityVO authorityVO = new AuthorityVO();
            BeanUtil.copyProperties(authority, authorityVO);
            authorityVO.setState(authority.getState() == 1);
            AuthorityVOList.add(authorityVO);
        }
        ListForm<AuthorityVO> roleListForm = new ListForm<>(authorityDTO.getPage(),authorityDTO.getSize(),
                authorityIPage.getPages(), //总页数
                authorityIPage.getTotal(), //总记录数
                AuthorityVOList);
        return R.succeed(roleListForm);
    }

    @Override
    public R insertAuthority(AddAuthorityDTO addAuthorityDTO) {
        Authority authority = new Authority();
        BeanUtil.copyProperties(addAuthorityDTO, authority);
        authority.setCreationTime(LocalDateTime.now());
        int insert = baseMapper.insert(authority);
        if (insert != 0){
            return R.succeed("添加成功");
        } else {
            return R.failed("添加失败");
        }
    }

    @Override
    public R updateAuthority(EditAuthorityDTO editAuthorityDTO) {
        Authority authority = new Authority();
        BeanUtil.copyProperties(editAuthorityDTO, authority);
        int update = baseMapper.updateById(authority);
        if (update != 0){
            return R.succeed("修改成功");
        } else {
            return R.failed("修改失败");
        }
    }

    @Override
    public R<?> EnableAuthority(Long ID) {
        // 创建一个 UpdateWrapper 对象
        UpdateWrapper<Authority> updateWrapper = new UpdateWrapper<>();
        // 设置 id 等于 userID 的条件
        updateWrapper.eq("id", ID);
        // 设置 state 属性为 false
        updateWrapper.set("state", true);
        // 执行更新操作
        boolean result = update(updateWrapper);
        // 根据更新结果返回相应的响应
        if (result) {
            return R.succeed("权限已成功启用");
        } else {
            return R.failed("启用权限失败");
        }
    }

    @Override
    public R<?> DisableAuthority(Long ID) {
        // 创建一个 UpdateWrapper 对象
        UpdateWrapper<Authority> updateWrapper = new UpdateWrapper<>();
        // 设置 id 等于 userID 的条件
        updateWrapper.eq("id", ID);
        // 设置 state 属性为 false
        updateWrapper.set("state", false);
        // 执行更新操作
        boolean result = update(updateWrapper);
        // 根据更新结果返回相应的响应
        if (result) {
            return R.succeed("权限已成功禁用");
        } else {
            return R.failed("禁用权限失败");
        }
    }

    @Override
    public List<Authority> getStateAuthorities() {
        QueryWrapper<Authority> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", 1);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public Boolean areAuthoritiesValid(List<Long> authoritiesIds) {
//        // 获取数据库中存在的权限列表
//        List<Authority> existingAuthorities = getStateAuthorities();
//        // 将数据库中存在的权限ID提取到一个集合中
//        Set<Long> existingAuthorityIds = existingAuthorities.stream()
//                .map(Authority::getId)
//                .collect(Collectors.toSet());
//        // 检查每个传入的权限ID是否存在于数据库中
//        for (Long authorityId :authoritiesIds) {
//            if (!existingAuthorityIds.contains(authorityId)) {
//                // 如果有任何一个权限ID不存在于数据库中，返回false
//                return false;
//            }
//        }
//        // 如果所有的权限ID都存在于数据库中，返回true
//        return true;
        // 获取所有存在且有效的权限
        List<Authority> validAuthorities = getStateAuthorities();
        // 将有效权限转换为ID列表
        Set<Long> validAuthoritiesIds = validAuthorities.stream()
                .map(Authority::getId)
                .collect(Collectors.toSet());
        // 检查传入的每个权限ID是否都在有效的权限ID集合中
        //检查每一个
        //return validAuthoritiesIds.containsAll(authoritiesIds);
        //空集也返回true
        return authoritiesIds.stream().allMatch(validAuthoritiesIds::contains);
    }

    @Override
    public Map<Long, Authority> getStateAuthoritiesMap() {
        // 从数据库获取角色列表
        List<Authority> Authorities = this.getStateAuthorities();
        // 使用 Java 8 Stream API 将 List<Authority> 转换为 Map<Long, Authority>
        return Authorities.stream()
                .collect(Collectors.toMap(Authority::getId, authority -> authority));
    }
}
